package com.sky.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品和对应的口味
     *
     * @param dishDTO
     * @return
     */
    @Transactional
    public Result<Object> saveWithFlavor(DishDTO dishDTO) {

        Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO, dish);

        //向菜品表插入1条数据
        dishMapper.insert(dish);

        //获取insert语句生成的主键值
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表插入数据
            dishFlavorMapper.insertBatch(flavors);

        }
        return Result.success();
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 删除菜品以及批量删除
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Result deleteDish(List<Long> ids) {
        //1.非空判断
        if(ids==null || ids.size()==0){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.查询当前菜品是否存在
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            //3.如果存在，判断状态如果是起售状态，则不能删除
            if(dish!=null){
                if(dish.getStatus()== StatusConstant.ENABLE){
                    return Result.error(MessageConstant.DISH_ON_SALE);
                }
            }
        }

        //4.如果存在，被套餐关联也不能删除
        List<Long> setmealDishIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealDishIds!=null && setmealDishIds.size()>0){
            return Result.error(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //5.如果存在，删除菜品之后，口味数据也删除
        dishMapper.deleteDish(ids);
        dishFlavorMapper.deleteDishFlavor(ids);

        //6.返回数据
        return Result.success();
    }

    /**
     * 根据id查询单个菜品
     *
     * @param id
     * @return
     */
    @Override
    public Result<DishVO> getById(Long id) {
        //1.非空判断
        if(id==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.根据id查询当前数据
        //2.1 查询菜品
        Dish dish = dishMapper.getById(id);
        //2.2查询口味
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getDishFalvorListById(id);

        //2.3 口味关联到菜品中
        DishVO vo=new DishVO();
        BeanUtils.copyProperties(dish,vo);
        vo.setFlavors(dishFlavorList);

        //3.如果存在，则返回数据
        return Result.success(vo);
    }

    /**
     * 根据id修改菜品信息
     * @param
     */
    @Override
    @Transactional
    public Result updateDish(DishDTO dto) {
        //1.非空判断
        if(dto.getId()==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.根据id修改dish表
        Dish dish=new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.updateDishById(dish);

        //3.根据菜品id去删除口味表数据集合
        dishFlavorMapper.deleteDishFlavor(Arrays.asList(dto.getId()));


        //4.插入新的口味数据到口味表中
        List<DishFlavor> flavors = dto.getFlavors();//每个DishFlavor只包含了name和value,并不包含dish_id
        if(flavors!=null && flavors.size()>0){
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
            dishFlavorMapper.insertBatch(flavors);
        }

        return Result.success();
    }

    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
     */
    @Transactional
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateDishById(dish);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getDishFalvorListById(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
